package com.yl.nettylearning.netty.day01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author yangl
 */
public class Server {
    public static void main(String[] args) throws Exception{
        //创建bossGroup和WorkerGroup
        //创建两个线程组bossGroup和workerGroup
        //bossGroup只是处理连接请求，真正的和客户端业务处理，是workerGroup
        //两个都是无限循环
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //创建服务器端的启动对象，配置启动参数
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //使用链式编程进行设置
        try {
            serverBootstrap.group(bossGroup, workerGroup)   //设置两个线程组
                    .channel(NioServerSocketChannel.class)  //使用nioSocketChannel，作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128)  //设置线程队列，得到连接数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)  //设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() { //创建一个通道，测试对象
                        //给pipeline设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    }); //给workerGroup的EventLoop对应 的管道设置处理器
            System.out.println("。。。。服务器 is ready。。。。");
            //绑定一个端口并且同步，生成一个ChannelFuture对象
            ChannelFuture cf = serverBootstrap.bind(6668).sync();
            cf.channel().closeFuture().sync();
        }finally {
            //发生异常，关闭netty
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
